#include "StdAfx.h"
#include "DeskTopSer.h"

HWND DeskTopSer::m_hWnd = NULL;

void CALLBACK DeskTopSer::threadWork_1(SOCKET s, int ServerPort, const char *ClientIP)
{
	Jpeg2RgbScreen * m_Jpeg2RgbScreen = new Jpeg2RgbScreen;
	if (!m_Jpeg2RgbScreen) return;

	m_Jpeg2RgbScreen->Init(NULL);
	::SendMessage(m_hWnd,WM_MSG_ACCEPT,(WPARAM)m_Jpeg2RgbScreen,(LPARAM)s);
	
	while(1)
	{
		ScreenHeader msg;	
		int ret = recv(s,(char*)&msg,sizeof(ScreenHeader),0);
		if (ret <= 0)
		{
			Sleep(500);
			continue;
		}	

		char * lpData  = (char *)GlobalAlloc(GMEM_FIXED,msg.dwFileSize +1);
		memset(lpData,0,msg.dwFileSize +1);
		int rev = 0;
		ret =-1;

		while(rev < msg.dwFileSize)
		{
			ret = recv(s,(char*)&lpData[rev],msg.dwFileSize-rev,0);
			if (ret < 0 )
			{
				break;	
			}

			rev += ret;
		}
		if (rev == msg.dwFileSize)
		{
			m_Jpeg2RgbScreen->SetScreenData(msg,(BYTE *)lpData);
			//m_Jpeg2RgbScreen->Set_BackGroud_Image();
		}

		if (lpData)
		{
			GlobalFree(lpData);
		}

	}
	/**free memory*/
	if(m_Jpeg2RgbScreen) 
	{
	    delete m_Jpeg2RgbScreen;
		m_Jpeg2RgbScreen = NULL;
	}

}

void DeskTopSer::printfNotify(char* error)
{

	::SetWindowText(m_hWnd,error);

}
int DeskTopSer::start(int port)
{
	if(server.CreateServer(port,5))
	server.StartServer(threadWork_1);
	return 0;
}

void  DeskTopSer::setHwnd(HWND hwnd)
{
	m_hWnd = hwnd;
}